package com.somlsis.activity

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.core.view.get
import com.base.AppConfig
import com.base.BaseActivity
import com.base.utils.LoadImageUtils
import com.base.utils.ToastUtils
import com.donkingliang.imageselector.utils.ImageSelector
import com.event.RefreshUserEvent
import com.net.HttpResponse
import com.somlsis.R
import com.somlsis.bean.Upload
import com.somlsis.bean.User
import com.somlsis.databinding.ActivityUserInfoBinding
import com.utils.DensityUtils
import com.widget.TimePickerCustom
import org.greenrobot.eventbus.Subscribe
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File

class UserInfoActivity : BaseActivity<ActivityUserInfoBinding>() {
    private val user = dataCenter.getUser()
    private val mRequestCode = 101
    private var picPath: String? = null
    private var gender = "0"
    private lateinit var genderAdapter: ArrayAdapter<String>
    override fun getViewBinding(): ActivityUserInfoBinding {
        return ActivityUserInfoBinding.inflate(LayoutInflater.from(this))
    }

    override fun createView() {
        binding.layoutTitle.title.text = getString(R.string.questions_and_comments)
        binding.layoutTitle.back.setOnClickListener {
            finish()
        }
        val stringArray = resources.getStringArray(R.array.gender_list)
        genderAdapter = ArrayAdapter<String>(context, R.layout.item_gender, stringArray)
        binding.gender.adapter = genderAdapter
        binding.birthdayLayout.setOnClickListener {
            TimePickerCustom(
                context, "选择生日", false
            ) { year: Int, month: Int, day: Int ->
                // 确定按钮的回调
                Log.i(
                    "timePickerCustom",
                    "$year------$month--------$day"
                )
                binding.birthday.text = "$year-$month"
            }.show()
        }
        binding.userAvatarLayout.setOnClickListener {
            ImageSelector.builder()
                .useCamera(true) // 设置是否使用拍照
                .setSingle(true)  //设置是否单选
                .canPreview(true) //是否可以预览图片，默认为true
                .start(this, mRequestCode); // 打开相册
        }
        binding.confirm.setOnClickListener {
            var userName = binding.userName.text.toString()
            var birthday = binding.birthday.text.toString()
            var userHeight = binding.userHeight.text.toString()
            var userWeight = binding.userWeight.text.toString()

            user?.let {
                if (userName.isEmpty()) {
                    userName = it.name
                }
                if (userHeight.isEmpty()) {
                    userHeight = it.height.toString()
                }
                if (userWeight.isEmpty()) {
                    userWeight = it.weight.toString()
                }
                if (picPath == null) {
                    picPath = it.phone
                } else {
                    picPath?.let { path ->
                        dataCenter.upload(path, object : Callback<HttpResponse<Upload>> {
                            override fun onResponse(
                                call: Call<HttpResponse<Upload>>,
                                response: Response<HttpResponse<Upload>>
                            ) {
                                response.body()?.let { body ->
                                    if (response.code() == AppConfig.SUCCEED_CODE) {
                                        dataCenter.editUser(userName,
                                            body.data.pic,
                                            birthday,
                                            gender,
                                            userHeight,
                                            userWeight,
                                            object : Callback<HttpResponse<User>> {
                                                override fun onResponse(
                                                    call: Call<HttpResponse<User>>,
                                                    response: Response<HttpResponse<User>>
                                                ) {
                                                    if (response.code() == AppConfig.SUCCEED_CODE) {
                                                        response.body()?.let { userBody ->
                                                            dataCenter.setUser(userBody.data)
                                                            finish()
                                                        }
                                                    }

                                                }

                                                override fun onFailure(
                                                    call: Call<HttpResponse<User>>,
                                                    t: Throwable
                                                ) {
                                                    ToastUtils.showTost(context, t.message)
                                                }

                                            })

                                    }
                                }
                            }

                            override fun onFailure(call: Call<HttpResponse<Upload>>, t: Throwable) {

                            }

                        })
                    }

                }
            }
        }
        binding.gender.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                gender = if (position == 0) {
                    "1"
                } else {
                    "2"
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

        }
        refreshUI()
    }

    private fun refreshUI() {
        user?.let {
            binding.userName.setText(it.name)
            binding.birthday.text = it.birth
            binding.userHeight.setText(it.height.toString())
            binding.userWeight.setText(it.weight.toString())
            if (it.sex == 1) {
                binding.gender.setSelection(0)
            } else {
                binding.gender.setSelection(1)
            }
            if (picPath != null) {
                LoadImageUtils.loadImageCircleCrop(binding.userAvatar, File(picPath))
            } else {
                LoadImageUtils.loadImageCircleCrop(binding.userAvatar, it.phone)
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            if (requestCode == mRequestCode) {
                //获取选择器返回的数据
                /**
                 * 是否是来自于相机拍照的图片，
                 * 只有本次调用相机拍出来的照片，返回时才为true。
                 * 当为true时，图片返回的结果有且只有一张图片。
                 */
                val isCameraImage = it.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false)
                if (isCameraImage) {
                    picPath = it.getStringExtra(ImageSelector.SELECT_RESULT)
                } else {
                    val list = it.getStringArrayListExtra(
                        ImageSelector.SELECT_RESULT
                    )
                    list?.let { data ->
                        picPath = data[0]
                    }

                }
                refreshUI()
            }
        }

    }

    @Subscribe
    fun onRefreshUserEvent(event: RefreshUserEvent) {
        refreshUI()
    }
}